import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

// 聊天消息类型
interface ChatMessage {
  id: string;
  role: 'user' | 'ai' | 'system';
  content: string;
  timestamp: number;
  status: 'sending' | 'sent' | 'failed' | 'received';
  type: 'text' | 'voice' | 'image';
  metadata?: {
    duration?: number; // 语音时长
    size?: number; // 文件大小
    url?: string; // 文件URL
  };
}

// 聊天会话类型
interface ChatSession {
  id: string;
  title: string;
  lastMessage: string;
  lastTime: number;
  unreadCount: number;
  isActive: boolean;
}

export const useChatStore = defineStore('chat', () => {
  // 状态管理
  const messages = ref<ChatMessage[]>([]);
  const sessions = ref<ChatSession[]>([]);
  const currentSessionId = ref<string>('');
  const isConnected = ref(false);
  const isLoading = ref(false);

  // 计算属性
  const currentSession = computed(() => 
    sessions.value.find(session => session.id === currentSessionId.value)
  );

  const currentMessages = computed(() => 
    messages.value.filter(msg => msg.id.startsWith(currentSessionId.value))
  );

  const unreadTotalCount = computed(() => 
    sessions.value.reduce((total, session) => total + session.unreadCount, 0)
  );

  // 设置聊天会话列表
  const setSessions = (sessionList: any[]) => {
    sessions.value = sessionList.map(session => ({
      id: session.id || '',
      title: session.title || 'AI助手',
      lastMessage: session.lastMessage || '',
      lastTime: session.lastTime || Date.now(),
      unreadCount: session.unreadCount || 0,
      isActive: session.isActive || false
    }));
  };

  // 添加新会话
  const addSession = (session: any) => {
    const newSession = {
      id: session.id || `session_${Date.now()}`,
      title: session.title || 'AI助手',
      lastMessage: session.lastMessage || '',
      lastTime: session.lastTime || Date.now(),
      unreadCount: session.unreadCount || 0,
      isActive: session.isActive || false
    };
    
    sessions.value.unshift(newSession);
  };

  // 切换当前会话
  const switchSession = (sessionId: string) => {
    currentSessionId.value = sessionId;
    
    // 更新会话状态
    sessions.value.forEach(session => {
      session.isActive = session.id === sessionId;
      if (session.id === sessionId) {
        session.unreadCount = 0; // 清除未读消息
      }
    });
  };

  // 添加消息
  const addMessage = (message: any) => {
    const newMessage = {
      id: message.id || `${currentSessionId.value}_${Date.now()}`,
      role: message.role || 'user',
      content: message.content || '',
      timestamp: message.timestamp || Date.now(),
      status: message.status || 'received',
      type: message.type || 'text',
      metadata: message.metadata || {}
    };

    messages.value.push(newMessage);

    // 更新会话的最后消息
    const session = sessions.value.find(s => s.id === currentSessionId.value);
    if (session) {
      session.lastMessage = newMessage.content;
      session.lastTime = newMessage.timestamp;
      
      // 如果不是当前会话，增加未读计数
      if (!session.isActive && newMessage.role === 'ai') {
        session.unreadCount++;
      }
    }

    return newMessage;
  };

  // 更新消息状态
  const updateMessageStatus = (messageId: string, status: ChatMessage['status']) => {
    const message = messages.value.find(msg => msg.id === messageId);
    if (message) {
      message.status = status;
    }
  };

  // 发送消息
  const sendMessage = async (content: string, type: 'text' | 'voice' = 'text', metadata?: any) => {
    const message = {
      role: 'user' as const,
      content,
      type,
      metadata,
      status: 'sending' as const
    };

    const newMessage = addMessage(message);

    try {
      // 这里应该调用WebSocket发送消息
      // 暂时模拟发送过程
      await new Promise(resolve => setTimeout(resolve, 500));
      
      updateMessageStatus(newMessage.id, 'sent');
      
      // 模拟AI回复
      setTimeout(() => {
        const aiResponse = {
          role: 'ai' as const,
          content: generateAIResponse(content),
          type: 'text' as const,
          status: 'received' as const
        };
        addMessage(aiResponse);
      }, 1000);

      return newMessage;
    } catch (error) {
      updateMessageStatus(newMessage.id, 'failed');
      throw error;
    }
  };

  // 接收消息
  const receiveMessage = (message: any) => {
    return addMessage({
      ...message,
      status: 'received'
    });
  };

  // 清除消息
  const clearMessages = (sessionId?: string) => {
    if (sessionId) {
      messages.value = messages.value.filter(msg => !msg.id.startsWith(sessionId));
    } else {
      messages.value = [];
    }
  };

  // 设置连接状态
  const setConnectionStatus = (connected: boolean) => {
    isConnected.value = connected;
  };

  // 设置加载状态
  const setLoading = (loading: boolean) => {
    isLoading.value = loading;
  };

  // 模拟AI回复生成
  const generateAIResponse = (userMessage: string): string => {
    const responses = [
      '我理解您的问题，让我为您分析一下...',
      '这是一个很好的问题，根据我的分析...',
      '关于节电方面，我建议您可以...',
      '根据您的情况，我推荐以下方案...',
      '让我为您提供一些实用的节电建议...'
    ];
    
    return responses[Math.floor(Math.random() * responses.length)];
  };

  // 初始化默认会话
  const initDefaultSession = () => {
    if (sessions.value.length === 0) {
      addSession({
        id: 'ai_assistant',
        title: 'AI节电助手',
        lastMessage: '您好，我是AI节电助手，有什么可以帮您？',
        lastTime: Date.now(),
        unreadCount: 0,
        isActive: true
      });
      currentSessionId.value = 'ai_assistant';
      
      // 添加欢迎消息
      addMessage({
        role: 'ai',
        content: '您好，我是AI节电助手，有什么可以帮您？',
        type: 'text',
        status: 'received'
      });
    }
  };

  return {
    // 状态
    messages,
    sessions,
    currentSessionId,
    isConnected,
    isLoading,
    
    // 计算属性
    currentSession,
    currentMessages,
    unreadTotalCount,
    
    // 方法
    setSessions,
    addSession,
    switchSession,
    addMessage,
    updateMessageStatus,
    sendMessage,
    receiveMessage,
    clearMessages,
    setConnectionStatus,
    setLoading,
    initDefaultSession
  };
});
